package nl.hengelsportmolenberg.boilies.client;

import nl.hengelsportmolenberg.boilies.client.event.EditCustomerEvent;
import nl.hengelsportmolenberg.boilies.client.event.EditCustomerEventHandler;
import nl.hengelsportmolenberg.boilies.client.presenter.CustomerCardPresenter;
import nl.hengelsportmolenberg.boilies.client.presenter.TestPresenter;
import nl.hengelsportmolenberg.boilies.client.presenter.Presenter;
import nl.hengelsportmolenberg.boilies.client.view.CustomerCardView;
import nl.hengelsportmolenberg.boilies.client.view.TestView;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;


public class AppControler implements Presenter, ValueChangeHandler<String> {
	private final HandlerManager eventBus;
	private final BoiliesServiceAsync rpcService;
	private HasWidgets container;

	public AppControler(BoiliesServiceAsync rpcService, HandlerManager eventBus) {
		this.eventBus = eventBus;
		this.rpcService = rpcService;
		bind();
	}
	
	private void bind() {
		History.addValueChangeHandler(this);
		
		eventBus.addHandler(EditCustomerEvent.TYPE,
			new EditCustomerEventHandler() {
				public void onEditCustomer(EditCustomerEvent event) {
					doEditCustomer(event.getId());
				}
			}
		);
	}
	
private void doEditCustomer(int id) {
	History.newItem("editcustomer");
}
		  

public void go(final HasWidgets container) {
    this.container = container;
    
    if ("".equals(History.getToken())) {
      History.newItem("test");
    }
    else {
      History.fireCurrentHistoryState();
    }
  }

  public void onValueChange(ValueChangeEvent<String> event) {
    String token = event.getValue();
    
    if (token != null) {
      Presenter presenter = null;

      if (token.equals("card")) {
    	  presenter = new CustomerCardPresenter(rpcService, eventBus, new CustomerCardView());
      }
      
      if (token.equals("test")) {
    	  presenter = new TestPresenter(new TestView());
      }
            
      if (presenter != null) {
        presenter.go(container);
      }
    }
  } 

}
